package utils

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

//const (
//	SessionKey = "clientUser"
//	SerSessKey = ""
//)

// UserInfo 用来解析从 session 中读取出来的用户数据
type UserInfo struct {
	Tid      int    `json:"tid"`
	UserName string `json:"userName"`
}

type Sess interface {
	SetSession(key, val string) error
	GetSession(key string) bool
	DelSession(key string)
}

type SessionKey struct {
	CliSessKey string
	SerSessKey string
}

type Session struct {
	Se     sessions.Session
	SesKey *SessionKey
}

func InitSession(c *gin.Context, key string) *Session {
	sess := &Session{}
	sess.Se = sessions.Default(c)
	switch key {
	case "admin":
		sess.SesKey = &SessionKey{SerSessKey: "adminUser"}
	case "client":
		sess.SesKey = &SessionKey{CliSessKey: "clientUser"}
	}
	return sess
}

func (s *Session) SetSession(key string, val interface{}) error {
	s.Se.Set(key, val)
	if err := s.Se.Save(); err != nil {
		return errors.New(fmt.Sprintf("后台服务器错误，给您带来不便抱歉！"))
	}
	return nil
}

func (s *Session) GetSession(key string) interface{} {
	get := s.Se.Get(key)
	if get == nil {
		return ""
	}
	return get
}

func (s *Session) DelSession(key string) {
	s.Se.Delete(key)
}

// SliceUint8ToMap 将Session 中获取到的数据转换成 Map
func (s *Session) SliceUint8ToMap(val interface{}) (dat *UserInfo, err error) {
	dat = &UserInfo{}
	if err = json.Unmarshal([]byte(string(val.(interface{}).([]uint8))), &dat); err != nil {
		return nil, errors.New(fmt.Sprintf("登录失败后台服务其错误，错误代码：%v", err))
	}
	return
}
